#coding=utf-8
'''
  This is a testing procedure!
'''
import re
import os
import tornado.ioloop
import tornado.web
from settings import db


def get_tags(content):
    r=re.compile(r"@([\u4E00-\u9FA5\w-]+)")
    return r.findall(content)
class BaseHandler(tornado.web.RequestHandler):
    def get_current_user(self):
        names=self.get_secure_cookie("user")
        print(names)
        return names
    
    
class WeiboHandler(BaseHandler):
    @tornado.web.authenticated
    def get(self):
        #return
    
        self.render("weibo_add.html")
    @tornado.web.authenticated    
    def post(self):
        result=self.get_body_argument("content","")
        
        #print(get_tags(result))
        for i in get_tags(result):
            print(i)
        
        #names1=self.get_current_user()
        #print("names1"+names1)
        db.weibo.insert({"content":result,"user":self.get_current_user()})
        self.write(result)    
class UserHandler(BaseHandler):
    @tornado.web.authenticated
    def get(self):
        user=self.get_current_user()
        return self.render("userinfo.html",**{"user":user})
class RegisterHandler(BaseHandler):
    def get(self):
        self.render("register.html")
    def post(self):
        account=self.get_argument("account")
        password=self.get_argument("password")
        if account =="" or password =="":
            return self.write("This is a register error!")    
        #if db.user.find({"account":account}).count()>0:  #the same is next centence
        if db.user.count({"account":account})>0:
            return self.write("This  account is exist!")    
        db.user.insert({"account":account,"password":password})
        self.write("Register success!")
        self.set_secure_cookie("user", self.get_argument("account"))
        self.redirect("/user")
        
class LoginHandler(BaseHandler):
    def get(self):
        #self.write('<html><body><form action="/login" method="post">'
        #           'Name: <input type="text" name="account">'
        #           '<input type="submit" value="Sign in">'
        #           '</form></body></html>')
        return self.render("login.html")    

    def post(self):
        #print("39999999999999")
        account=self.get_argument("account")
        password=self.get_argument("password")
        
        if account=="" or password=="":
            return self.write("account or password is NULL")
        if db.user.find({"account":account}).count()==0:
            return self.write("No account!")
        if db.user.find({"account":account,"password":password}).count()==0:
            return self.write("no password!")
        self.set_secure_cookie("user", self.get_argument("account"))
        self.redirect("/")
        
        
class MainHandler(BaseHandler):
    @tornado.web.authenticated
    def get(self):
        name = tornado.escape.xhtml_escape(self.current_user)
             
        self.write("Hello, " + name)
class UsersHandler(BaseHandler):
    @tornado.web.authenticated
#    def get(self):
#        users=db.user.find()
#        self.render("users_html.html",**{"users1":users})
    def get(self):
        followed_users=db.follow.find({"user":self.get_current_user()},{"follow_user":1})
        filter_users=[follow["follow_user"]for follow in followed_users]
        filter_users.append(self.get_current_user())
        users=db.user.find({"account":{"$nin":filter_users}})
        self.render("users_html.html",**{"users1":users})
         
            
class FollowHandler(BaseHandler):       
    @tornado.web.authenticated
    def get(self):
        user2=self.get_argument("follow_current_user",None)
        if not user2:
            return self.redirect("/users") 
        db.follow.insert({"follow_user":user2,"user":self.get_current_user()})   
        #print(user2)
        self.redirect("/followed")
    
        
class FollowedHandler(BaseHandler):       
    @tornado.web.authenticated
    def get(self):
        user=db.follow.find({"user":self.get_current_user()})
        #print(user)
        self.render("follow_user.html",**{"follow_user1":user})  

settings = {
    #"cookie_secret": "__TODO:_GENERATE_YOUR_OWN_RANDOM_VALUE_HERE__",
    "cookie_secret": "kajiuewrhuioweir23903939eeiwofoiewiorioiojrjoijweioriiweiiweiriqrw",
    "login_url": "/login",
    "template_path":os.path.join(os.path.dirname(__file__),"templates"),
    "debug":True
}
application = tornado.web.Application([
    (r"/", MainHandler),
    (r"/login", LoginHandler),
    (r"/Register",RegisterHandler),
    (r"/weibo/add",WeiboHandler),
    (r"/user",UserHandler),
    (r"/users",UsersHandler),
    (r"/follow",FollowHandler),
    (r"/followed",FollowedHandler)
    
], **settings)

if __name__=="__main__":
    application.listen(8888)
    tornado.ioloop.IOLoop.instance().start()

        